//
//  MYGScheduleOverviewViewController.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/5/29.
//

import UIKit
import JXSegmentedView
import MJRefresh

class MYGScheduleOverviewViewController: MYGBaseController {
    var meeting_id:String = ""
    private var page = 1
    private var selectIndex = 0
    private var searchStr = ""
    private var contents:[MYGAcademicModel] = []
    private var speechArra:[MYGAcademicSpeechModel] = []
    private var expertArra:[MYGAcademicExpertListModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        configUI()
        tableView.mj_header?.beginRefreshing()
    }
    
    private func configUI() {
        self.title = "日程一览"
        view.backgroundColor = .white
        
        view.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview().inset(15)
            make.height.equalTo(30)
        }
        
        view.addSubview(segmentView)
        segmentView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.height.equalTo(48)
            make.width.equalTo(200)
            make.top.equalTo(searchTextField.snp.bottom).offset(15)
        }
        view.addSubview(line)
        line.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(0.5)
            make.top.equalTo(segmentView.snp.bottom).offset(15)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(line.snp.bottom)
            make.bottom.equalToSuperview()
        }
        
    }
  
    
    private lazy var searchTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(142, 142, 147, 1)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 15
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Chat/search"))
            confer.text(" 请输入标题或讲者搜索")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        tf.textAlignment = .center
        tf.delegate = self
//        tf.addTarget(self, action: #selector(textValueChanged), for: .editingChanged)
        return tf
    }()
    
    private lazy var segmentView: JXSegmentedView = {
        let segment = JXSegmentedView()
        segment.delegate = self
        segment.dataSource = dataSource
        segment.backgroundColor = .rgba(255, 255, 255, 1)
        return segment
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["论坛", "讲题","专家"]
        dataSource.titleNormalFont = .regular(15)
        dataSource.titleNormalColor = .rgba(118, 118, 118, 1)
        dataSource.titleSelectedFont = .medium(18)
        dataSource.titleSelectedColor = .rgba(32, 92, 255, 1)
        return dataSource
    }()
    private lazy var line:UIView = {
        let line = UIView()
        line.backgroundColor = .rgba(238, 238, 238, 1)
        return line
    }()
    
    private lazy var tableView: UITableView = {
        let tableV = UITableView()
        tableV.backgroundColor = .rgba(245, 245, 245, 1)
        tableV.delegate = self
        tableV.dataSource = self
        tableV.separatorStyle = .none
        tableV.showsVerticalScrollIndicator = false
        tableV.register(cellWithClass: MYGMettingForumCell.self)
        tableV.register(cellWithClass: MYGExpertTableViewCell.self)
        tableV.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getList()
        })
        
        tableV.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getList()
        })
        return tableV
    }()
    
}
extension MYGScheduleOverviewViewController:UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if textField.text?.count ?? 0 > 0 {
            searchStr = textField.text!
        }else {
            searchStr = ""
        }
        getList()
        return true
    }
    
}
extension MYGScheduleOverviewViewController {
    
    //论坛
    private func getList(){
        if selectIndex == 0 {
            getData()
        }else if selectIndex == 1 {
            getSpeechList()
        }else {
            getExportList()
        }
    }
    
    private func getData(){
        var params :[String:Any] = [:]
        params["meeting_id"] = meeting_id
        params["type"] = "\(selectIndex + 1)"
        params["key"] = searchStr
        params["page"] = page
        params["pageSize"] = 20
        
        MYGLoading.show()
        MMYGNetwork<MYGHomePageAPI, MYGPageModel<MYGAcademicModel>>.request(target: .foreign(param: params)) { result in
            MYGLoading.hide()
            guard let item = result else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.contents = item.list
            } else {
                self.contents.append(contentsOf: item.list)
            }
            
            if item.page.total <= self.contents.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.tableView.reloadData()
            
        } failed: { _, error in
            self.tableView.mj_header?.endRefreshing()
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    // 专家
    private func getExportList(){
        var params :[String:Any] = [:]
        params["meeting_id"] = meeting_id
        params["type"] = "\(selectIndex + 1)"
        params["key"] = searchStr
        params["page"] = page
        params["pageSize"] = 20
        
        MYGLoading.show()
        MMYGNetwork<MYGHomePageAPI, MYGPageModel<MYGAcademicExpertListModel>>.request(target: .foreign(param: params)) { result in
            MYGLoading.hide()
            guard let item = result else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.expertArra = item.list
            } else {
                self.expertArra.append(contentsOf: item.list)
            }
            
            if item.page.total <= self.expertArra.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.tableView.reloadData()
            
        } failed: { _, error in
            self.tableView.mj_header?.endRefreshing()
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
        
    }
    // 讲题
    private func getSpeechList(){
        
        var params :[String:Any] = [:]
        params["meeting_id"] = meeting_id
        params["type"] = "\(selectIndex + 1)"
        params["key"] = searchStr
        params["page"] = page
        params["pageSize"] = 20
        
        MYGLoading.show()
        MMYGNetwork<MYGHomePageAPI, MYGPageModel<MYGAcademicSpeechModel>>.request(target: .foreign(param: params)) { result in
            MYGLoading.hide()
            guard let item = result else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.speechArra = item.list
            } else {
                self.speechArra.append(contentsOf: item.list)
            }
            if item.page.total <= self.speechArra.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.tableView.reloadData()
            
        } failed: { _, error in
            self.tableView.mj_header?.endRefreshing()
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
}
extension MYGScheduleOverviewViewController: JXSegmentedViewDelegate {

    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        selectIndex = index
        self.contents.removeAll()
        self.expertArra.removeAll()
        self.speechArra.removeAll()
        self.page = 1
        if index == 0 {
            getData()
        }else if index == 1 {
            getSpeechList()
        }else {
            getExportList()
        }
    }
}
extension MYGScheduleOverviewViewController:UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if selectIndex == 2 {
            return expertArra.count
        }
        return selectIndex == 0 ? contents.count  : speechArra.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if selectIndex == 2 {
            return 82.5
        }
        return selectIndex == 0 ? 114 : 139
     }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if selectIndex == 2 {
            let cell = tableView.dequeueReusableCell(withClass: MYGExpertTableViewCell.self)
            cell.model = self.expertArra[indexPath.row]
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withClass: MYGMettingForumCell.self)
        cell.isShow = selectIndex == 0
        if (selectIndex == 0) {
            cell.model = self.contents[indexPath.row]
        }else {
            cell.sppeechModel = self.speechArra[indexPath.row]
        }
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if selectIndex == 0 {
            let model = self.contents[indexPath.row]
            let vc = MYGAcademicSchuledDetailVC()
            vc.id = "\(model.id)"
            self.navigationController?.pushViewController(vc)
        }else if selectIndex == 1 {
            let model = self.speechArra[indexPath.row]
            let vc = MYGAcademicSchuledDetailVC()
            vc.id = "\(model.room_id)"
            self.navigationController?.pushViewController(vc)
        }else {
            let model = self.expertArra[indexPath.row]
            let vc = MYGExpertTaskDetailViewController()
            vc.id = model.id
            self.navigationController?.pushViewController(vc)
        }
        
    }
    
}
